﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;

namespace CSharpWheels.Librarys.Exceptions
{
    /// <summary>Represents errors that occur during application execution.</summary>
    /// <typeparam name="TExceptionArgs">The type of exception and any additional arguments associated with it.</typeparam>
    [Serializable]
    public sealed class Exception<TExceptionArgs> : Exception, ISerializable where TExceptionArgs : ExceptionArgs
    {
        private const String c_args = "Args";     // For (de)serialization
        private readonly TExceptionArgs m_args;

        /// <summary>Returns a reference to this exception's additional arguments.</summary>
        public TExceptionArgs Args { get { return m_args; } }

        /// <summary>
        /// Initializes a new instance of the Exception class with a specified error message 
        /// and a reference to the inner exception that is the cause of this exception. 
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="innerException">The exception that is the cause of the current exception, 
        /// or a null reference if no inner exception is specified.</param>
        public Exception(String message = null, Exception innerException = null)
           : this(null, message, innerException) { }

        // The fourth public constructor because there is a field
        /// <summary>
        /// Initializes a new instance of the Exception class with additional arguments, 
        /// a specified error message, and a reference to the inner exception 
        /// that is the cause of this exception. 
        /// </summary>
        /// <param name="args">The exception's additional arguments.</param>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="innerException">The exception that is the cause of the current exception, 
        /// or a null reference if no inner exception is specified.</param>
        public Exception(TExceptionArgs args, String message = null, Exception innerException = null)
           : base(message, innerException)
        {
            m_args = args;
        }

        //这个构造器用于反序列化，因为是密封类，所以可以使用private,如果类 不是密封的，这个构造函数必须是 protected（因为派生类需要能访问它）
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        private Exception(SerializationInfo info, StreamingContext context)
           : base(info, context)
        { // Let the base deserialize its fields
            m_args = (TExceptionArgs)info.GetValue(c_args, typeof(TExceptionArgs));
        }

        //用于控制对象的序列化过程,它定义了对象如何将自己的数据转换为序列化格式 info.AddValue(c_args, m_args)
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(c_args, m_args);
            base.GetObjectData(info, context);
        }

        /// <summary>Gets a message that describes the current exception.</summary>
        public override String Message
        {
            get
            {
                String baseMsg = base.Message;
                return (m_args == null) ? baseMsg : baseMsg + " (" + m_args.Message + ")";
            }
        }

        /// <summary>
        /// Determines whether the specified Object is equal to the current Object.
        /// </summary>
        /// <param name="obj">The Object to compare with the current Object. </param>
        /// <returns>true if the specified Object is equal to the current Object; otherwise, false.</returns>
        public override Boolean Equals(Object obj)
        {
            Exception<TExceptionArgs> other = obj as Exception<TExceptionArgs>;
            if (other == null) return false;
            return Object.Equals(m_args, other.m_args) && base.Equals(obj);
        }
        public override int GetHashCode() { return base.GetHashCode(); }
    }

    /// <summary>
    /// A base class that a custom exception would derive from in order to add its own exception arguments.
    /// </summary>
    [Serializable]
    public abstract class ExceptionArgs
    {
        /// <summary>The string message associated with this exception.</summary>
        public virtual String Message { get { return String.Empty; } }
    }
}
